<template>
  <div class="container">
    <h1>大文件上传和下载</h1>
    <main>
      <section>
        <input type="file" @change="fileChange" ref="file">
        <button>下载</button>
      </section>
      <section>
        {{url}}
      </section>
      <section>
        <progress style="width: 400px;height: 50px" :value="progress" max="100"></progress>
      </section>
      <section>
        <div class="log">
          <p>日志</p>
          <p v-for="item in  log">{{ item }}</p>
        </div>
      </section>
    </main>

  </div>
</template>
<script setup>
import {ref} from "vue";
import {createChunks, hash} from "@/utils/utils.js";
import {checkApi, mergeApi, uploadApi} from "@/api/index.js";

let progress = ref(0)
let log = ref([])
let chunkSize = 1024 * 1024 * 0.1  //每片 m
let chunks = []
let chunkIndex = 0
let file
let fileHash
let url = ref("")
let fileName
const fileChange = async (e) => {
  if (!e) return
  file = e.target.files[0];
  fileName = file.name
  console.log(file)
  chunks = createChunks(file, chunkSize)
  console.log(chunks)
  fileHash = await hash(chunks)
  try {
    let res = await checkApi({
      file_hash: fileHash
    })
    if (res.data?.isHas) {
      url.value = res.data.url
      alert("文件已存在")
      return
    }
  } catch (e) {
    alert("检查文件失败")
    return
  }
  await startUpload()
}
const startUpload = async () => {
  console.log("开始", fileHash)
  for (chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
    try {
      await uploadApi({file: chunks[chunkIndex]}, {
        headers: {
          "fileHash": fileHash,
          "chunkIndex": chunkIndex,
          'content-type': "multipart/form-data"
        }
      })
      log.value.unshift(`分片：${chunkIndex}----${fileHash}上传成功`)
    } catch (e) {
      alert("上传失败")
      break
    }

  }
  try {
    let res = await mergeApi({file_hash: fileHash, file_name: fileName})
    url.value = res.data.url
  } catch (e) {
    alert("合并失败")
  }

}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  padding: 200px;
  flex-direction: column;
  gap: 40px;

  h1 {
    text-align: center;
    width: 100%;
  }
}

main {
  display: flex;
  flex-direction: column;
  gap: 40px;
}

section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
